<?php

namespace App\Http\Controllers\Chat\Api;

use App\Http\Controllers\Chat\BaseController;
use App\Models\Api\Friend;
use App\Models\Api\User;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use WebSocket\Client;
use function env;

class FriendController extends BaseController
{
    private $user;

    public function __construct(Request $request)
    {
        $access_token = $request->input('access_token');
        $this->user = User::with('friends')->whereLastLoginToken($access_token)->first();
    }

    public function addFriend(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->all();
        try {
            if(empty($data['user_name'])) {
                return ApiResponseTrait::error('好友用户名不能为空');
            }

            // 1、判断要申请好友用户是否存在
            $friend = User::whereUserName($data['user_name'])->whereStatus(User::STATUS_ON)->first();
            if(empty($friend->id)) {
                return ApiResponseTrait::error('用户不存在');
            }
            // 2、好友 id 不能是自己
            if($friend['id'] === $this->user->id) {
                return ApiResponseTrait::error('不能添加自己位好友！');
            }
            // 3、判断是否已经为好友关系
            if(Friend::isFriend($this->user->id, $friend['id'])) {
                return ApiResponseTrait::error('对方已是您的好友！');
            }
            // 4、判断是否发送过重复的好友申请
            $user_cache = $this->getSocket($friend->id);
            if(!empty($user_cache['apply_list'])) {
                foreach ($user_cache['apply_list'] as $key => $item) {
                    if($key === $this->user->id) {
                        return ApiResponseTrait::error('已发出好友申请，请勿重复申请！');
                    }
                }
            }

            $send = [
                'type' => 'addFriend',
                'uid' => $this->user->id,
                'user_name' => $this->user->user_name,
                'target' => $friend->id,
                'message' => $data['message']
            ];
            $client = new Client('ws://' . env('APP_DOMAIN') . ':9502?type=public&access_token=' . $data['access_token']);
            $client->send(json_encode($send));
            $receive = json_decode($client->receive(), true);
            if($receive['code'] === 0){ // 执行成功
                $client->close();
            }

            return ApiResponseTrait::success([], '好友申请已发送！');
        } catch (\Exception $exception) {
            return ApiResponseTrait::error($exception->getMessage());
        }
    }

    public function handleFriend(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->all();
        try {
            if(empty($data['desc']) || !in_array($data['desc'], [1, 2])) {
                return ApiResponseTrait::error('处理结果不能为空');
            }
            if(empty($data['target'])) {
                return ApiResponseTrait::error('好友不能为空');
            }

            $user_cache = $this->getSocket($this->user->id);
            if(empty($user_cache['apply_list']) || !array_key_exists($data['target'], $user_cache['apply_list'])) {
                return ApiResponseTrait::error('该好友申请不存在！');
            }

            $message = '拒绝添加好友！';
            DB::beginTransaction();
            if($data['desc'] == 1) {
                // 存储好友关系
                $create1 = Friend::create([
                    'uid' => $data['target'],
                    'fid' => $this->user->id,
                ]);
                $create2 = Friend::create([
                    'uid' => $this->user->id,
                    'fid' => $data['target'],
                ]);
                if($create1 === false || $create2 === false) {
                    DB::rollBack();
                    return ApiResponseTrait::error('添加好友失败');
                }
                $message = '同意添加好友！';
            }

            unset($user_cache['apply_list'][$data['target']]);
            $this->setSocket($this->user->id, $user_cache);

            DB::commit();

            // 通知对方处理结果
            $send = [
                'type' => 'handleFriend',
                'uid' => $data['target'],
                'user_name' => $this->user->user_name,
                'target' => $this->user->id,
                'message' => $message,
                'desc' => $data['desc'],
            ];
            $client = new Client('ws://' . env('APP_DOMAIN') . ':9502?type=handleFriend&access_token=' . $data['access_token']);
            $client->send(json_encode($send));
            $receive = json_decode($client->receive(), true);
            if($receive['code'] === 0){ // 执行成功
                $client->close();
            }

            return ApiResponseTrait::success([], '好友申请处理完成');
        } catch (\Exception $exception) {
            return ApiResponseTrait::error($exception->getMessage());
        }
    }

    public function friendList(Request $request): \Illuminate\Http\JsonResponse
    {
        $list = Friend::leftjoin('users', 'users.id', '=', 'friends.fid')->where('friends.uid', '=', $this->user->id)->get(['users.id', 'user_name']);
        return ApiResponseTrait::success($list->toArray());
    }

    public function delFriend(Request $request)
    {

    }
}
